package indi.cyh.fastservice.annotation.validator;

import com.alibaba.fastjson.JSONObject;
import indi.cyh.fastservice.annotation.IsJson;
import indi.cyh.jdbctool.tool.StringTool;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 校验是否是json字符串
 *
 * @Description TODO
 * @Author CYH
 * @Date 2021/7/20 19:22
 **/
public class IsJsonValidator implements ConstraintValidator<IsJson, String> {
    // 是否强制校验
    private boolean required;

    @Override
    public void initialize(IsJson constraintAnnotation) {
        this.required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (!StringTool.isEmpty(value)) {
            try {
                JSONObject.parseObject(value);
            } catch (Exception e) {
                return false;
            }
        }
        return true;
    }
}
